﻿
using OF.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using Microsoft.Web.Infrastructure;
using OF.Utility.Logging;

namespace User.Api.Filters
{
    /// <summary>
    /// 用户权限验证
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class APIAuthorizationFilterAttribute : AuthorizationFilterAttribute
    {

        /// <summary>
        /// 重写权限验证
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            Log4netLog.Debug("User.Api.Api");
            StringBuilder sb = new StringBuilder();
            //如果用户方位的Action带有AllowAnonymousAttribute，则不进行授权验证
            if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any())
            {
                return;
            }

            sb.AppendLine("权限验证失败：");
            sb.AppendLine("IP：" + OF.Utility.IPHelper.IPAddress);
            sb.AppendFormat("UserAgent：" + HttpContext.Current.Request.UserAgent);

            //获取Header请求的标识(格式：Scheme Parameter)
            var authorization = actionContext.Request.Headers.Authorization;
            if (authorization == null)
            {
                sb.AppendLine("错误信息：Missing Authorization");
                
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "Missing Authorization");
                return;
            }

            if (!authorization.Scheme.Equals("BMCW", StringComparison.OrdinalIgnoreCase))
            {
                sb.AppendLine("错误信息：Missing Scheme Or Error Scheme");
         
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "Missing Scheme Or Error Scheme");
                return;
            }

            if (String.IsNullOrEmpty(authorization.Parameter))
            {
                sb.AppendLine("错误信息：Missing Authorization Parameter");
             
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "Missing Authorization Parameter");
                return;
            }

            if (!ValidAuthParameter(actionContext, authorization.Parameter))
            {
                sb.AppendLine("错误信息：Error Authorization Parameter ");
             
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "Error Authorization Parameter ");
                return;
            }

            //内部验证
            SetPrincipal(actionContext, authorization.Parameter, sb);

            //同一个IP固定时间的访问次数限制(防止定时攻击)
        }

        /// <summary>
        /// 权限验证
        /// </summary>
        /// <param name="actionContext">action上下文</param>
        /// <param name="authParam">身份验证信息</param>
        /// <param name="sb"></param>
        protected void SetPrincipal(HttpActionContext actionContext, string authParam, StringBuilder sb)
        {
            string userId = GetHeaderValue(actionContext, "appuser");
            APIIdentity ident = new APIIdentity(userId);
            actionContext.RequestContext.Principal = new APIPrincipal(ident);
        }

        /// <summary>
        /// 验证BASIC
        /// </summary>
        /// <param name="actionContext"></param>
        /// <param name="authParam"></param>
        /// <returns></returns>
        protected bool ValidAuthParameter(HttpActionContext actionContext, string authParam)
        {
            //app固定的可以
            string key = "cgs";
            string url = actionContext.Request.RequestUri.AbsoluteUri;
            string ms = authParam.Substring(0, 3);
            string token;
            if (url.Length > 32)
            {
                token = key + url.Substring(8, 24) + ms;
            }
            else
            {
                token = key + url.Substring(9) + ms;
            }
            string md5 = MD5Helper.MD5String(token);
            return md5.Equals(authParam.Substring(3));
        }

        /// <summary>
        /// 获取制定的header值
        /// </summary>
        /// <param name="actionContext"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public string GetHeaderValue(HttpActionContext actionContext, string name)
        {
            IEnumerable<string> headers;
            if (actionContext.Request.Headers.TryGetValues(name, out headers))
            {
                return headers.FirstOrDefault();

            }
            return "";
        }

    }
}